package com.example.choupaiapp.main.activity.home;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;

import com.example.choupaiapp.R;
import com.example.choupaiapp.common.ui.activity.CommonActivity;
import com.example.choupaiapp.common.view.NoScrollViewPager;
import com.example.choupaiapp.common.view.TabEntity;
import com.example.choupaiapp.main.activity.publish.PublishNewActivity;
import com.example.choupaiapp.main.bean.CameraDataBean;
import com.example.choupaiapp.main.callback.RedBookPresenter;
import com.example.choupaiapp.main.fragment.home.TakePhotoFragment;
import com.example.choupaiapp.main.fragment.home.TakeVideoFragment;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.orhanobut.logger.Logger;
import com.ypx.imagepicker.ImagePicker;
import com.ypx.imagepicker.activity.crop.MultiImageCropFragment;
import com.ypx.imagepicker.bean.ImageItem;
import com.ypx.imagepicker.bean.MimeType;
import com.ypx.imagepicker.bean.PickerError;
import com.ypx.imagepicker.data.OnImagePickCompleteListener2;
import com.ypx.imagepicker.helper.PickerErrorExecutor;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.BindView;

/**
 * Created by ASUS on 2019/12/9.
 */

public class CameraActivity extends CommonActivity {

    @BindView(R.id.viewpager)
    NoScrollViewPager viewpager;
    @BindView(R.id.common_bottom_tab)
    CommonTabLayout commonBottomTab;
    private ArrayList<Fragment> mFragments = new ArrayList<>();//存放Fragment

    private String[] mTitles;

    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    public static View view;
    private MultiImageCropFragment mFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_camera);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (null != viewpager) {
            viewpager.setCurrentItem(0);
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void OnMessageEvent(String event) {
        if (event.equals("finish_camera")) {
            finishActivity();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Override
    protected void initView() {

        EventBus.getDefault().register(this);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String flag = bundle.getString("flag");
            int count = bundle.getInt("count");
            if ("out".equals(flag)) {
                mTitles = new String[3];
                mTitles[0] = "相册";

                mFragment = ImagePicker.withCrop(new RedBookPresenter())//设置presenter
                        .setMaxCount(count)//设置选择数量
                        .showCamera(false)//设置显示拍照
                        .setColumnCount(4)//设置列数
                        .mimeTypes(MimeType.ofAll())//设置需要加载的文件类型
                        // .filterMimeType(MimeType.GIF)//设置需要过滤掉的文件类型
                        .assignGapState(false)
//                        .setFirstImageItem(resultList.size() > 0 ? resultList.get(0) : null)//设置上一次选中的图片
                        .setVideoSinglePick(true)//设置视频单选
//                        .setSinglePickWithAutoComplete(false)
                        .setMaxVideoDuration(120000L)//设置可选区的最大视频时长
                        .setMinVideoDuration(3000L)
                        .pickWithFragment(new OnImagePickCompleteListener2() {
                            @Override
                            public void onPickFailed(PickerError error) {
                                PickerErrorExecutor.executeError(CameraActivity.this, error.getCode());
                            }

                            @Override
                            public void onImagePickComplete(ArrayList<ImageItem> items) {
                                Logger.e(items.get(0).getUri().toString()+"+++++"+items.get(0).getPath());
                                Logger.e(items.get(0).getTimeFormat());
                                ArrayList<String> list = new ArrayList<>();
                                for (int i = 0; i < items.size(); i++) {
                                    list.add(items.get(i).getPath());
                                }
                                Bundle bundle = new Bundle();
                                bundle.putString("flag", "no_text");
                                if (items.get(0).getMimeType().startsWith("video")) {
                                    bundle.putString("isVideo", "yes");
                                } else {
                                    bundle.putString("isVideo", "no");
                                }
                                bundle.putString("shootTime", items.get(0).getTimeFormat());
                                bundle.putStringArrayList("path", list);
                                startFinishActivity(PublishNewActivity.class, bundle);
                            }
                        });

                mFragments.add(mFragment);

                mTitles[1] = "拍照";
                TakePhotoFragment takePhotoFragment = TakePhotoFragment.newInstance("out");
                mFragments.add(takePhotoFragment);

                mTitles[2] = "拍视频";
                TakeVideoFragment takeVideoFragment = TakeVideoFragment.newInstance("out");
                mFragments.add(takeVideoFragment);
            } else {
                String isEmpty = bundle.getString("isEmpty");
                if ("yes".equals(isEmpty)) {
                    mTitles = new String[3];
                    mTitles[0] = "相册";

                    mFragment = ImagePicker.withCrop(new RedBookPresenter())//设置presenter
                            .setMaxCount(count)//设置选择数量
                            .showCamera(false)//设置显示拍照
                            .setColumnCount(4)//设置列数
                            .mimeTypes(MimeType.ofAll())//设置需要加载的文件类型
                            // .filterMimeType(MimeType.GIF)//设置需要过滤掉的文件类型
                            .assignGapState(false)
//                        .setFirstImageItem(resultList.size() > 0 ? resultList.get(0) : null)//设置上一次选中的图片
                            .setVideoSinglePick(true)//设置视频单选
//                        .setSinglePickWithAutoComplete(false)
                            .setMaxVideoDuration(120000L)//设置可选区的最大视频时长
                            .setMinVideoDuration(3000L)
                            .pickWithFragment(new OnImagePickCompleteListener2() {
                                @Override
                                public void onPickFailed(PickerError error) {
                                    PickerErrorExecutor.executeError(CameraActivity.this, error.getCode());
                                }

                                @Override
                                public void onImagePickComplete(ArrayList<ImageItem> items) {
                                    ArrayList<String> list = new ArrayList<>();
                                    for (int i = 0; i < items.size(); i++) {
                                        list.add(items.get(i).getPath());
                                    }

                                    CameraDataBean cameraDataBean = new CameraDataBean();
                                    cameraDataBean.setFlag("no_text");
                                    cameraDataBean.setTime(items.get(0).getTimeFormat());
                                    if (items.get(0).getMimeType().startsWith("video")) {
                                        cameraDataBean.setIsVideo("yes");
                                    } else {
                                        cameraDataBean.setIsVideo("no");
                                    }
                                    cameraDataBean.setList(list);
                                    EventBus.getDefault().post(cameraDataBean);
                                    finishActivity();
                                }
                            });

                    mFragments.add(mFragment);

                    mTitles[1] = "拍照";
                    TakePhotoFragment takePhotoFragment = TakePhotoFragment.newInstance("in_yes");
                    mFragments.add(takePhotoFragment);

                    mTitles[2] = "拍视频";
                    TakeVideoFragment takeVideoFragment = TakeVideoFragment.newInstance("in_yes");
                    mFragments.add(takeVideoFragment);
                } else {
                    mTitles = new String[2];
                    mTitles[0] = "相册";

                    mFragment = ImagePicker.withCrop(new RedBookPresenter())//设置presenter
                            .setMaxCount(count)//设置选择数量
                            .showCamera(false)//设置显示拍照
                            .setColumnCount(4)//设置列数
                            .mimeTypes(MimeType.ofImage())//设置需要加载的文件类型
                            // .filterMimeType(MimeType.GIF)//设置需要过滤掉的文件类型
                            .assignGapState(false)
//                        .setFirstImageItem(resultList.size() > 0 ? resultList.get(0) : null)//设置上一次选中的图片
                            .setVideoSinglePick(true)//设置视频单选
//                        .setSinglePickWithAutoComplete(false)
                            .setMaxVideoDuration(120000L)//设置可选区的最大视频时长
                            .setMinVideoDuration(3000L)
                            .pickWithFragment(new OnImagePickCompleteListener2() {
                                @Override
                                public void onPickFailed(PickerError error) {
                                    PickerErrorExecutor.executeError(CameraActivity.this, error.getCode());
                                }

                                @Override
                                public void onImagePickComplete(ArrayList<ImageItem> items) {
                                    ArrayList<String> list = new ArrayList<>();
                                    for (int i = 0; i < items.size(); i++) {
                                        list.add(items.get(i).getPath());
                                    }
                                    CameraDataBean cameraDataBean = new CameraDataBean();
                                    cameraDataBean.setFlag("no_text");
                                    cameraDataBean.setTime(items.get(0).getTimeFormat());
                                    if (items.get(0).getMimeType().startsWith("video")) {
                                        cameraDataBean.setIsVideo("yes");
                                    } else {
                                        cameraDataBean.setIsVideo("no");
                                    }
                                    cameraDataBean.setList(list);
                                    EventBus.getDefault().post(cameraDataBean);
                                    finishActivity();
                                }
                            });

                    mFragments.add(mFragment);

                    mTitles[1] = "拍照";
                    TakePhotoFragment takePhotoFragment = TakePhotoFragment.newInstance("in_no");
                    mFragments.add(takePhotoFragment);

                }
            }
        }


        commonBottomTab.setTextSelectColor(getResources().getColor(R.color.white));

        for (int i = 0; i < mFragments.size(); i++) {
            mTabEntities.add(new TabEntity(mTitles[i]));
        }

        viewpager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
        commonBottomTab.setTabData(mTabEntities);

        view = View.inflate(context, R.layout.cameraview_layout, null);

        commonBottomTab.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                if (position == 0) {
                    try {
                        if (((TakeVideoFragment) mFragments.get(2)).camera != null) {
                            ((TakeVideoFragment) mFragments.get(2)).camera.destroy();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    try {
                        if (((TakePhotoFragment) mFragments.get(1)).camera != null) {
                            ((TakePhotoFragment) mFragments.get(1)).camera.destroy();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else if (position == 1) {
                    try {
                        if (((TakeVideoFragment) mFragments.get(2)).camera != null) {
                            ((TakeVideoFragment) mFragments.get(2)).camera.destroy();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    EventBus.getDefault().post("takephoto");
                } else if (position == 2) {
                    try {
                        if (((TakePhotoFragment) mFragments.get(1)).camera != null) {
                            ((TakePhotoFragment) mFragments.get(1)).camera.destroy();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    EventBus.getDefault().post("takevideo");
                }
                viewpager.setCurrentItem(position);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

//        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
//            @Override
//            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//
//            }
//
//            @Override
//            public void onPageSelected(int position) {
//                if (position == 0) {
//                    try {
//                        if (((TakeVideoFragment) mFragments.get(2)).camera != null) {
//                            ((TakeVideoFragment) mFragments.get(2)).camera.destroy();
//                        }
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//
//                    try {
//                        if (((TakePhotoFragment) mFragments.get(1)).camera != null) {
//                            ((TakePhotoFragment) mFragments.get(1)).camera.destroy();
//                        }
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                } else if (position == 1) {
//                    try {
//                        if (((TakeVideoFragment) mFragments.get(2)).camera != null) {
//                            ((TakeVideoFragment) mFragments.get(2)).camera.destroy();
//                        }
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                    EventBus.getDefault().post("takephoto");
//                } else if (position == 2) {
//                    try {
//                        if (((TakePhotoFragment) mFragments.get(1)).camera != null) {
//                            ((TakePhotoFragment) mFragments.get(1)).camera.destroy();
//                        }
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                    EventBus.getDefault().post("takevideo");
//                }
//                commonBottomTab.setCurrentTab(position);
//            }
//
//            @Override
//            public void onPageScrollStateChanged(int state) {
//
//            }
//        });

        viewpager.setCurrentItem(0);
        viewpager.setOffscreenPageLimit(5);
    }

    @Override
    protected void initData() {

    }

    private class MyPagerAdapter extends FragmentPagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles[position];
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
//            super.destroyItem(container, position, object);
        }
    }

    @Override
    public void onBackPressed() {
        if (mFragment != null && mFragment.onBackPressed()) {
            return;
        }
        super.onBackPressed();
    }

}
